//
//  AYBLEDevice.m
//  FuweiCloud
//
//  Created by michael on 2024/4/29.
//

#import "AYBLEDevice.h"
#import "AYBLEParameter.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "NSData+AYExtension.h"
#if __has_include(<AYBLECore/AYBLEManager.h>)
#import <AYBLECore/AYBLEManager.h>
#else
#import "AYBLEManager.h"
#endif

@interface AYBLEDevice ()
@property (nonatomic, strong) CBPeripheral *peripheral;

///< 设备名称
@property (nonatomic, copy) NSString *name;

///< 设备mac地址
@property (nonatomic, copy) NSString *mac;

///< 设备是否绑定
@property (nonatomic, assign) BOOL binded;

@property (nonatomic, assign) AYBLEDeviceMatchType match_num;
@property (nonatomic, assign) NSInteger manufaturer_id;

@end

@implementation AYBLEDevice

+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"peripheral"];
}

- (instancetype)initWithAdvertisementData:(NSDictionary *)advData peripheral:(CBPeripheral *)peripheral prefixes:(nonnull NSArray<NSString *> *)prefixes {
    if (self = [super init]) {
        _peripheral = peripheral;
        ///< 设备名称
        _name = advData[CBAdvertisementDataLocalNameKey];
        ///< 厂商数据
        NSData *mfrData = advData[CBAdvertisementDataManufacturerDataKey];
        AYBLELogger(2,@"adv data:%@",advData);
        _match_num = AYBLEDeviceMatchTypeQ0;
       if ([prefixes indexOfObjectPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
            return [_name hasPrefix:obj];
        }] != NSNotFound) {
            if (mfrData.length > 10) {
                _mac = AYDataFromLen(mfrData, 0, 6).ay_hex;
                _match_num = AYDataFromLen(mfrData, 6, 1).ay_int8;
                _sn = [[NSString alloc] initWithData:AYDataFromLen(mfrData, 9, mfrData.length - 9) encoding:NSUTF8StringEncoding];
            }else {
                AYBLELogger(1,@"设备广播信息长度错误: %@, length: %ld",_name, mfrData.length);
            }
        }
        AYBLELogger(2,@"设备名称：%@",_name);
        AYBLELogger(2,@"设备MAC地址：%@",_mac);
        AYBLELogger(2,@"设备绑定状态：%d",_binded);
        AYBLELogger(2,@"设备配对值：%ld",_match_num);
    }
    return self;
}

- (NSString *)mac_format {
    if (_mac.length != 12) return @"";
    NSString *mf = @"";
    for (int i = 0; i < _mac.length; i+=2) {
        mf = [mf stringByAppendingFormat:@"%@%@",[_mac substringWithRange:NSMakeRange(i, 2)].lowercaseString,(i==(_mac.length-2))?@"":@":"];
    }
    return mf;
}

- (void)dealloc {
    NSLog(@"[device:%@ dealloc]",self.mac);
}

@end
